<template>
  <div class="identity-verification">
    <div class="container">
      <!-- 认证状态显示 -->
      <el-card class="status-card">
        <div class="status-content">
          <div class="status-icon">
            <el-icon 
              :size="48" 
              :color="getStatusColor()"
            >
              <component :is="getStatusIcon()" />
            </el-icon>
          </div>
          <div class="status-info">
            <h3>{{ getStatusTitle() }}</h3>
            <p>{{ getStatusDescription() }}</p>
          </div>
        </div>
        
        <div v-if="identityStatus.status === 'verified'" class="verified-info">
          <div class="info-item">
            <span class="label">认证姓名：</span>
            <span class="value">{{ maskName(identityStatus.realName) }}</span>
          </div>
          <div class="info-item">
            <span class="label">身份证号：</span>
            <span class="value">{{ maskIdCard(identityStatus.idCard) }}</span>
          </div>
          <div class="info-item">
            <span class="label">认证时间：</span>
            <span class="value">{{ formatDate(identityStatus.verifiedAt) }}</span>
          </div>
        </div>

        <div v-if="identityStatus.status === 'rejected'" class="rejected-reason">
          <h4>审核未通过原因：</h4>
          <p>{{ identityStatus.rejectReason }}</p>
          <el-button type="primary" @click="showVerificationForm = true">
            重新认证
          </el-button>
        </div>
      </el-card>

      <!-- 认证须知 -->
      <el-card class="notice-card">
        <h3>实名认证须知</h3>
        <div class="notice-content">
          <div class="notice-section">
            <h4>为什么需要实名认证？</h4>
            <ul>
              <li>保障您的账户安全，防止身份盗用</li>
              <li>享受更高级的服务权限和优惠</li>
              <li>提升服务商家对您的信任度</li>
              <li>符合国家相关法律法规要求</li>
            </ul>
          </div>

          <div class="notice-section">
            <h4>认证所需材料</h4>
            <ul>
              <li>本人二代身份证正面照片</li>
              <li>本人二代身份证反面照片</li>
              <li>确保照片清晰，信息完整可见</li>
              <li>身份证在有效期内</li>
            </ul>
          </div>

          <div class="notice-section">
            <h4>隐私保护承诺</h4>
            <ul>
              <li>您的个人信息将严格保密</li>
              <li>仅用于身份验证，不会用于其他用途</li>
              <li>采用银行级加密技术保护数据安全</li>
              <li>符合《个人信息保护法》相关规定</li>
            </ul>
          </div>
        </div>
      </el-card>

      <!-- 认证表单 -->
      <el-card 
        v-if="shouldShowForm()" 
        class="form-card"
      >
        <h3>身份认证</h3>
        <el-form 
          :model="verificationForm" 
          :rules="verificationRules" 
          ref="verificationFormRef"
          label-width="100px"
        >
          <el-form-item label="真实姓名" prop="realName">
            <el-input
              v-model="verificationForm.realName"
              placeholder="请输入身份证上的真实姓名"
              maxlength="20"
            />
          </el-form-item>

          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="verificationForm.idCard"
              placeholder="请输入18位身份证号码"
              maxlength="18"
            />
          </el-form-item>

          <el-form-item label="身份证正面" prop="idCardFront">
            <div class="upload-section">
              <el-upload
                class="id-card-uploader"
                :action="uploadAction"
                :show-file-list="false"
                :on-success="handleFrontSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                accept="image/*"
              >
                <img 
                  v-if="verificationForm.idCardFront" 
                  :src="verificationForm.idCardFront" 
                  class="id-card-image"
                />
                <div v-else class="upload-placeholder">
                  <el-icon><Plus /></el-icon>
                  <div class="upload-text">上传身份证正面</div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <p>请上传身份证正面照片</p>
                <p>支持JPG、PNG格式，大小不超过5MB</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="身份证反面" prop="idCardBack">
            <div class="upload-section">
              <el-upload
                class="id-card-uploader"
                :action="uploadAction"
                :show-file-list="false"
                :on-success="handleBackSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                accept="image/*"
              >
                <img 
                  v-if="verificationForm.idCardBack" 
                  :src="verificationForm.idCardBack" 
                  class="id-card-image"
                />
                <div v-else class="upload-placeholder">
                  <el-icon><Plus /></el-icon>
                  <div class="upload-text">上传身份证反面</div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <p>请上传身份证反面照片</p>
                <p>确保国徽和签发机关清晰可见</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="verificationForm.agreement">
              我已阅读并同意
              <el-link type="primary" @click="showAgreement">《实名认证协议》</el-link>
            </el-checkbox>
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              @click="submitVerification"
              :loading="submitting"
              :disabled="!verificationForm.agreement"
            >
              提交认证
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 认证权益 -->
      <el-card class="benefits-card">
        <h3>认证后享受的权益</h3>
        <div class="benefits-grid">
          <div class="benefit-item">
            <el-icon :size="32" color="#67c23a"><Medal /></el-icon>
            <h4>实名标识</h4>
            <p>账户显示实名认证标识，提升信誉度</p>
          </div>
          <div class="benefit-item">
            <el-icon :size="32" color="#409eff"><Gift /></el-icon>
            <h4>专享优惠</h4>
            <p>获得实名用户专属优惠券和活动</p>
          </div>
          <div class="benefit-item">
            <el-icon :size="32" color="#e6a23c"><CreditCard /></el-icon>
            <h4>免押金</h4>
            <p>部分服务可享受免押金特权</p>
          </div>
          <div class="benefit-item">
            <el-icon :size="32" color="#f56c6c"><Shield /></el-icon>
            <h4>安全保障</h4>
            <p>账户安全等级提升，资金更安全</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 认证协议对话框 -->
    <el-dialog v-model="showAgreementDialog" title="实名认证协议" width="700px">
      <div class="agreement-content">
        <h4>1. 服务条款</h4>
        <p>用户同意提供真实、准确、完整的个人身份信息用于实名认证...</p>
        
        <h4>2. 隐私保护</h4>
        <p>我们承诺严格保护用户隐私，不会将用户身份信息用于认证以外的其他用途...</p>
        
        <h4>3. 认证责任</h4>
        <p>用户对提供的身份信息真实性负责，如因虚假信息造成的后果由用户承担...</p>
        
        <h4>4. 信息使用</h4>
        <p>认证信息仅用于身份验证、风险控制、法律合规等必要用途...</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAgreementDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Medal,
  Gift,
  CreditCard,
  Shield,
  SuccessFilled,
  Loading,
  WarningFilled,
  InfoFilled
} from '@element-plus/icons-vue'
import { settingsApi } from '@/services/api'
import dayjs from 'dayjs'

// 数据定义
const submitting = ref(false)
const showVerificationForm = ref(false)
const showAgreementDialog = ref(false)
const verificationFormRef = ref()
const uploadAction = '/api/upload/image' // 上传接口地址

// 认证状态
const identityStatus = ref({
  status: 'none', // none, pending, verified, rejected
  realName: '',
  idCard: '',
  verifiedAt: '',
  rejectReason: ''
})

// 认证表单
const verificationForm = reactive({
  realName: '',
  idCard: '',
  idCardFront: '',
  idCardBack: '',
  agreement: false
})

// 表单验证规则
const verificationRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5·]+$/, message: '请输入正确的中文姓名', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的身份证号码', 
      trigger: 'blur' 
    }
  ],
  idCardFront: [
    { required: true, message: '请上传身份证正面照片', trigger: 'change' }
  ],
  idCardBack: [
    { required: true, message: '请上传身份证反面照片', trigger: 'change' }
  ]
}

// 生命周期
onMounted(() => {
  fetchIdentityStatus()
})

// 方法定义
const fetchIdentityStatus = async () => {
  try {
    const response = await settingsApi.getIdentityStatus()
    identityStatus.value = response.data
    
    // 如果未认证，显示认证表单
    if (identityStatus.value.status === 'none') {
      showVerificationForm.value = true
    }
  } catch (error) {
    console.error('获取认证状态失败:', error)
  }
}

const shouldShowForm = () => {
  return showVerificationForm.value || 
         identityStatus.value.status === 'none' || 
         identityStatus.value.status === 'rejected'
}

const getStatusIcon = () => {
  const iconMap = {
    none: InfoFilled,
    pending: Loading,
    verified: SuccessFilled,
    rejected: WarningFilled
  }
  return iconMap[identityStatus.value.status] || InfoFilled
}

const getStatusColor = () => {
  const colorMap = {
    none: '#909399',
    pending: '#e6a23c',
    verified: '#67c23a',
    rejected: '#f56c6c'
  }
  return colorMap[identityStatus.value.status] || '#909399'
}

const getStatusTitle = () => {
  const titleMap = {
    none: '未认证',
    pending: '认证审核中',
    verified: '已实名认证',
    rejected: '认证未通过'
  }
  return titleMap[identityStatus.value.status] || '未知状态'
}

const getStatusDescription = () => {
  const descMap = {
    none: '请完成实名认证，享受更多服务权益',
    pending: '您的认证信息正在审核中，请耐心等待（通常1-3个工作日）',
    verified: '您已完成实名认证，可以享受全部服务功能',
    rejected: '认证信息未通过审核，请重新提交正确信息'
  }
  return descMap[identityStatus.value.status] || '状态异常'
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPG) {
    ElMessage.error('只支持JPG和PNG格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

const handleFrontSuccess = (response) => {
  verificationForm.idCardFront = response.data.url
  ElMessage.success('身份证正面上传成功')
}

const handleBackSuccess = (response) => {
  verificationForm.idCardBack = response.data.url
  ElMessage.success('身份证反面上传成功')
}

const handleUploadError = () => {
  ElMessage.error('图片上传失败，请重试')
}

const submitVerification = async () => {
  try {
    const valid = await verificationFormRef.value.validate()
    if (!valid) return

    if (!verificationForm.agreement) {
      ElMessage.warning('请先阅读并同意实名认证协议')
      return
    }

    await ElMessageBox.confirm(
      '请确认提交的信息真实有效，提交后无法修改',
      '确认提交',
      {
        confirmButtonText: '确认提交',
        cancelButtonText: '再次检查',
        type: 'warning'
      }
    )

    submitting.value = true

    const submitData = {
      realName: verificationForm.realName,
      idCard: verificationForm.idCard,
      idCardFront: verificationForm.idCardFront,
      idCardBack: verificationForm.idCardBack
    }

    await settingsApi.submitIdentity(submitData)
    
    ElMessage.success('认证信息提交成功！审核结果将在1-3个工作日内通知您')
    
    // 更新状态
    identityStatus.value.status = 'pending'
    showVerificationForm.value = false
    
    // 重置表单
    resetForm()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交认证失败:', error)
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  verificationFormRef.value?.resetFields()
  verificationForm.idCardFront = ''
  verificationForm.idCardBack = ''
  verificationForm.agreement = false
}

const showAgreement = () => {
  showAgreementDialog.value = true
}

const maskName = (name) => {
  if (!name) return ''
  if (name.length <= 2) return name
  return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1]
}

const maskIdCard = (idCard) => {
  if (!idCard) return ''
  return idCard.substring(0, 6) + '*'.repeat(8) + idCard.substring(14)
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style lang="scss" scoped>
.identity-verification {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.el-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.status-card {
  .status-content {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;

    .status-info {
      flex: 1;

      h3 {
        margin: 0 0 8px 0;
        font-size: 20px;
        color: #333;
      }

      p {
        margin: 0;
        color: #666;
        line-height: 1.5;
      }
    }
  }

  .verified-info {
    background: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;

    .info-item {
      display: flex;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        min-width: 80px;
        color: #666;
        font-size: 14px;
      }

      .value {
        color: #333;
        font-size: 14px;
        font-weight: 500;
      }
    }
  }

  .rejected-reason {
    background: #fef0f0;
    border: 1px solid #fbc4c4;
    border-radius: 8px;
    padding: 16px;

    h4 {
      margin: 0 0 8px 0;
      color: #f56c6c;
      font-size: 14px;
    }

    p {
      margin: 0 0 16px 0;
      color: #666;
      line-height: 1.5;
    }
  }
}

.notice-card {
  h3 {
    margin: 0 0 16px 0;
    font-size: 18px;
    color: #333;
  }

  .notice-content {
    .notice-section {
      margin-bottom: 24px;

      &:last-child {
        margin-bottom: 0;
      }

      h4 {
        margin: 0 0 12px 0;
        font-size: 16px;
        color: #333;
        border-left: 3px solid #409eff;
        padding-left: 12px;
      }

      ul {
        margin: 0;
        padding-left: 20px;
        color: #666;

        li {
          margin-bottom: 4px;
          line-height: 1.5;
        }
      }
    }
  }
}

.form-card {
  h3 {
    margin: 0 0 24px 0;
    font-size: 18px;
    color: #333;
  }

  .upload-section {
    display: flex;
    gap: 16px;
    align-items: flex-start;

    .id-card-uploader {
      flex-shrink: 0;

      :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 8px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;

        &:hover {
          border-color: #409eff;
        }
      }

      .id-card-image {
        width: 200px;
        height: 126px;
        object-fit: cover;
        display: block;
      }

      .upload-placeholder {
        width: 200px;
        height: 126px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #8c939d;
        background: #fafafa;

        .el-icon {
          font-size: 28px;
          margin-bottom: 8px;
        }

        .upload-text {
          font-size: 14px;
        }
      }
    }

    .upload-tips {
      flex: 1;
      color: #999;
      font-size: 12px;
      line-height: 1.5;

      p {
        margin: 0 0 4px 0;
      }
    }
  }
}

.benefits-card {
  h3 {
    margin: 0 0 16px 0;
    font-size: 18px;
    color: #333;
  }

  .benefits-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 20px;

    .benefit-item {
      text-align: center;
      padding: 20px;
      background: #fafafa;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        background: #f0f9ff;
        transform: translateY(-2px);
      }

      h4 {
        margin: 12px 0 8px 0;
        font-size: 16px;
        color: #333;
      }

      p {
        margin: 0;
        color: #666;
        font-size: 14px;
        line-height: 1.4;
      }
    }
  }
}

.agreement-content {
  color: #333;
  line-height: 1.6;
  max-height: 400px;
  overflow-y: auto;

  h4 {
    margin: 16px 0 8px 0;
    font-size: 16px;
    color: #333;

    &:first-child {
      margin-top: 0;
    }
  }

  p {
    margin: 0 0 12px 0;
    color: #666;
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .status-content {
    flex-direction: column;
    text-align: center;
  }

  .upload-section {
    flex-direction: column;

    .id-card-uploader {
      align-self: center;
    }

    .upload-tips {
      text-align: center;
    }
  }

  .benefits-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;

    .benefit-item {
      padding: 16px;
    }
  }

  .verified-info,
  .rejected-reason {
    .info-item {
      flex-direction: column;
      gap: 4px;

      .label {
        min-width: auto;
      }
    }
  }
}
</style> 